#pragma once
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include "Log.hpp"
extern Log lg;
const int backlog = 10;
enum
{
    SocketErr = 1,
    BindErr,
    ListenErr,
    ConnectErr
};
class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == -1)
        {
            lg(Fatal, "socket error, errno:%d, strerror:%s\n", errno, strerror(errno));
            exit(SocketErr);
        }
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        int len = sizeof(local);
        int n = bind(_sockfd, (struct sockaddr *)&local, len);
        if (n == -1)
        {
            lg(Fatal, "bind error, errno:%d, strerror:%s\n", errno, strerror(errno));
            exit(BindErr);
        }
    }
    void Listen()
    {
        int n = listen(_sockfd, backlog);
        if (n == -1)
        {
            lg(Fatal, "listen error, errno:%d, strerror:%s\n", errno, strerror(errno));
            exit(ListenErr);
        }
    }
    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd, (struct sockaddr *)&client, &len);
        if (newfd == -1)
        {
            lg(Warning, "accept error, errno:%d, strerror:%s\n", errno, strerror(errno));
            return -1;
        }
        //网络序列转主机序列
        char ipstr[32];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        *clientport = ntohs(client.sin_port);
        *clientip = ipstr;
        return newfd;
    }
    bool Connect(std::string& ip, uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));
        socklen_t len = sizeof(peer);

        int n = connect(_sockfd, (struct sockaddr *)&peer, len);

        if (n == -1)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }
    int Fd()
    {
        return _sockfd;
    }
    void Close()
    {
        close(_sockfd);
    }
public:
    int _sockfd;
};